import { t } from 'i18next'
import { fetchCheckMccInfo, fetchCreateConfs, fetchSetCookie } from '@/api/global'
import { CreateConfsParams } from '@/api/global/interface'
import { MEETING_JUMP_URL } from '@/utils/constant'
import { Modal, ModalInstance } from '@kedacom/react-next'
import React, { useRef } from 'react'
/**
 * 会议召开（1-及时会议; 3-个人模板; 4-根据虚拟会议室创会; 5-预约会议提前召开; 6-e164号）
 */
export default function useCreateConfs() {
	const modalInstance = useRef<ModalInstance | null>(null)
	const cb = useRef<null | ((meetingMoid: string) => void)>(null)
	const run = (params: CreateConfsParams, callBack?: (meetingMoid: string) => void) => {
		cb.current = callBack ?? null
		modalInstance.current = Modal.confirm({
			title: t('提示'),
			content: <div>{t('正在召开会议，请稍候...')}</div>,
			needFooter: false,
			onCancel: () => {
				modalInstance.current?.hide()
			},
		})
		fetchCreateConfs(params).then((res) => {
			if (res.success) {
				checkMccInfo(res.meeting_id)
			} else {
				let desc = res.description ?? t('操作失败')
				modalInstance.current?.update({
					title: t('提示'),
					content: <div>{desc}</div>,
					okText: false,
					cancelText: t('关闭'),
					needFooter: true,
					onCancel: () => {
						if (res.error_code === 51107) {
							checkMccInfo()
						} else {
							window.location.reload()
						}
						modalInstance.current?.hide()
					},
				})
			}
		})
	}
	const checkMccInfo = (meetingMoid?: string) => {
		fetchCheckMccInfo(meetingMoid).then((res) => {
			if (res.success) {
				if (!meetingMoid) return
				if (cb.current) {
					cb.current(meetingMoid)
					modalInstance.current?.hide()
				} else {
					fetchSetCookie(
						{
							meeting_moid: meetingMoid,
							type: 1,
						},
						() => {
							window.location.href = MEETING_JUMP_URL + '/mcc/manager/' + meetingMoid
						}
					)
				}
			} else {
				let desc = res.description ?? t('操作失败')
				modalInstance.current?.update({
					title: t('提示'),
					content: <div>{desc}</div>,
					okText: false,
					cancelText: t('关闭'),
					needFooter: true,
					onCancel: () => {
						window.location.reload()
						modalInstance.current?.hide()
					},
				})
			}
		})
	}
	return { run }
}
